import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 购物车数据存储在本地存储中
const CART_STORAGE_KEY = 'shopping_cart'

// 从本地存储加载购物车数据
const loadCartFromStorage = () => {
  try {
    const stored = localStorage.getItem(CART_STORAGE_KEY)
    return stored ? JSON.parse(stored) : []
  } catch (error) {
    console.error('加载购物车数据失败:', error)
    return []
  }
}

// 保存购物车数据到本地存储
const saveCartToStorage = (items) => {
  try {
    localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(items))
  } catch (error) {
    console.error('保存购物车数据失败:', error)
  }
}

export const useCartStore = defineStore('cart', () => {
  const cartItems = ref(loadCartFromStorage())
  const loading = ref(false)
  const error = ref(null)
  
  const totalItems = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.quantity, 0)
  })
  
  const totalPrice = computed(() => {
    return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
  })
  
  const fetchCart = async () => {
    loading.value = true
    error.value = null
    try {
      // 从本地存储加载购物车数据
      cartItems.value = loadCartFromStorage()
    } catch (err) {
      error.value = err.message
      console.error('获取购物车失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  const addToCart = async (product, quantity = 1) => {
    try {
      const existingItem = cartItems.value.find(item => item.productId === product.id)
      
      if (existingItem) {
        // 更新现有商品数量
        existingItem.quantity += quantity
      } else {
        // 添加新商品到购物车
        const cartItem = {
          id: Date.now(), // 使用时间戳作为ID
          productId: product.id,
          name: product.name,
          price: product.price,
          quantity: quantity,
          image: product.image
        }
        cartItems.value.push(cartItem)
      }
      
      // 保存到本地存储
      saveCartToStorage(cartItems.value)
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const removeFromCart = async (itemId) => {
    try {
      cartItems.value = cartItems.value.filter(item => item.id !== itemId)
      // 保存到本地存储
      saveCartToStorage(cartItems.value)
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const updateQuantity = async (itemId, quantity) => {
    if (quantity <= 0) {
      await removeFromCart(itemId)
      return
    }
    
    try {
      const item = cartItems.value.find(item => item.id === itemId)
      if (item) {
        item.quantity = quantity
        // 保存到本地存储
        saveCartToStorage(cartItems.value)
      }
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const clearCart = async () => {
    try {
      cartItems.value = []
      // 清空本地存储
      saveCartToStorage([])
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const isInCart = (productId) => {
    return cartItems.value.some(item => item.productId === productId)
  }
  
  return {
    cartItems,
    loading,
    error,
    totalItems,
    totalPrice,
    fetchCart,
    addToCart,
    removeFromCart,
    updateQuantity,
    clearCart,
    isInCart
  }
})